<template>
  <div class="app-container">
    <div class="filter-container">
      <SearchOptionUser :type="listQuery.type" @setSearchUserId="searchUserId" />
      <el-select v-model="listQuery.老师分类" placeholder="老师分类" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in teacherClassifyOption" :key="key" :label="value" :value="key" />
      </el-select>
      <el-select v-model="listQuery.is_show" placeholder="是否App显示" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in isShowOption" :key="key" :label="value" :value="key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" width="80">
        <template slot-scope="{row}">
          <img :src="returnImageUrl(row.photo)" alt="" class="avatar" style="width: 50px;height: 50px">
        </template>
      </el-table-column>
      <el-table-column label="学校邮箱" align="center">
        <template slot-scope="{row}">
          <span>{{ row.school_email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主职称" align="center">
        <template slot-scope="{row}">
          <span>{{ JSON.parse(row.append_json).主职称 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="老师分类" align="center">
        <template slot-scope="{row}">
          <span>{{ teacherClassifyOption[JSON.parse(row.append_json).老师分类] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否App显示" align="center">
        <template slot-scope="{row}">
          <span>{{ isShowOption[row.is_show] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <!--          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">-->
          <!--            删除-->
          <!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="头像" prop="photo" height="50px">
          <ImageUpload :upload-name="uploadName" :upload-image-url="returnImageUrl(temp.photo)" @getReturnImageUrl="setReturnImageUrl" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="学校邮箱" prop="school_email">
          <el-input v-model="temp.school_email" />
        </el-form-item>
        <el-form-item label="个人邮箱" prop="self_email">
          <el-input v-model="temp.self_email" />
        </el-form-item>
        <el-form-item label="是否App显示">
          <el-select v-model="temp.is_show" prop="is_show" class="filter-item">
            <el-option v-for="(value,key) in isShowOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="老师身份">
          <el-select v-model="temp.老师身份" prop="老师身份" class="filter-item">
            <el-option v-for="(value,key) in teacherIdentifyOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="老师分类">
          <el-select v-model="temp.老师分类" prop="老师分类" class="filter-item">
            <el-option v-for="(value,key) in teacherClassifyOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机" prop="手机">
          <el-input v-model="temp.mobile" />
        </el-form-item>
        <el-form-item label="电话" prop="电话">
          <el-input v-model="temp.电话" />
        </el-form-item>
        <el-form-item label="单位" prop="单位">
          <el-input v-model="temp.单位" />
        </el-form-item>
        <el-form-item label="主职称" prop="主职称">
          <el-input v-model="temp.主职称" />
        </el-form-item>
        <el-form-item label="其他职务职称" prop="其他职务职称">
          <el-input v-model="temp.其他职务职称" />
        </el-form-item>
        <el-form-item label="工作地点" prop="工作地点">
          <el-input v-model="temp.工作地点" />
        </el-form-item>
        <el-form-item label="专业方向" prop="专业方向">
          <el-input v-model="temp.专业方向" :autosize="{ minRows: 4, maxRows: 8}" type="textarea" />
        </el-form-item>
        <el-form-item label="学术成果" prop="学术成果">
          <el-input v-model="temp.学术成果" :autosize="{ minRows: 4, maxRows: 8}" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userPage, userCreate, userUpdate, userDelete } from '@/api/user'
import waves from '@/directive/waves' // waves directive
import { notifySuccess, formatJson, listQueryFilter, my_confirm, getFileUrl } from '@/utils/tool'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import SearchOptionUser from '@/components/SearchOption/user'
import ImageUpload from '@/components/Upload/ImageUpload'

export default {
  name: 'UserTeacherPage',
  components: { Pagination, SearchOptionUser, ImageUpload },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: { // 查询初始值
        page: 1,
        limit: 20,
        type: 1,
        name: undefined,
        老师分类: ''
      },
      isShowOption: {
        0: '不显示',
        1: '显示'
      },
      teacherIdentifyOption: {
        1: '老师',
        2: '助理',
        3: '隐藏人员VIP'
      },
      teacherClassifyOption: {
        1: '中心老师',
        2: '授课老师',
        3: '两者都是'
      },
      temp: {
        id: undefined,
        type: 1,
        name: '',
        password: '',
        school_email: '',
        self_email: '',
        is_show: '',
        mobile: '',
        photo: '',
        老师身份: '',
        老师分类: '',
        电话: '',
        单位: '',
        主职称: '',
        其他职务职称: '',
        专业方向: '',
        学术成果: ''
      },
      dialogFormVisible: false,
      uploadName: 'UpLoadImage',
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        name: [{ required: true, message: '姓名名称必填', trigger: 'change' }],
        school_email: [{ required: true, message: '学校邮箱名称必填', trigger: 'change' }],
        is_show: [{ required: true, message: '是否app显示必填', trigger: 'change' }],
        photo: [{ required: true, message: '头像必填', trigger: 'change' }],
        老师身份: [{ required: true, message: '老师身份必填', trigger: 'change' }],
        老师分类: [{ required: true, message: '老师分类必填', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      userPage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        name: '',
        photo: '',
        type: 1,
        school_email: '',
        self_email: '',
        is_show: '',
        mobile: '',
        password: '',
        老师身份: '',
        老师分类: '',
        电话: '',
        单位: '',
        主职称: '',
        其他职务职称: '',
        专业方向: '',
        学术成果: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          userCreate(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      // 渲染自定义属性
      this.temp.id = row.id
      this.temp.name = row.name
      this.temp.password = ''
      this.temp.school_email = row.school_email
      this.temp.self_email = row.self_email
      this.temp.is_show = row.is_show
      this.temp.mobile = row.mobile
      this.temp.photo = row.photo
      this.temp.老师身份 = JSON.parse(row.append_json).老师身份
      this.temp.老师分类 = JSON.parse(row.append_json).老师分类
      this.temp.电话 = JSON.parse(row.append_json).电话
      this.temp.单位 = JSON.parse(row.append_json).单位
      this.temp.主职称 = JSON.parse(row.append_json).主职称
      this.temp.其他职务职称 = JSON.parse(row.append_json).其他职务职称
      this.temp.工作地点 = JSON.parse(row.append_json).工作地点
      this.temp.专业方向 = JSON.parse(row.append_json).专业方向
      this.temp.学术成果 = JSON.parse(row.append_json).学术成果
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          if (tempData.password === '') {
            delete tempData.password
          }
          userUpdate(tempData).then(() => {
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        userDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['名称', '学号', '学校邮箱', '个人邮箱']
        const filterVal = ['name', 'number', 'school_email', 'self_email']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户学生表'
        })
        this.downloadLoading = false
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    returnImageUrl(photo) {
      return getFileUrl(photo)
    },
    searchUserId: function(data) { // 触发子组件城市选择-选择城市的事件
      this.listQuery.id = data.userId // 改变了父组件的值
    },
    setReturnImageUrl: function(data) {
      this.temp.photo = data
      notifySuccess(this, '头像上传成功,请点击确定修改')
    }
  }
}
</script>
